package front

import (
	"geekai/api/dto/response"
	"geekai/api/handler"
	"geekai/core"
	"geekai/model"
	"geekai/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ProductHandler struct {
	handler.BaseHandler
}

func NewProductHandler(app *core.AppServer, db *gorm.DB) *ProductHandler {
	return &ProductHandler{
		handler.BaseHandler{
			App: app,
			DB:  db,
		},
	}
}

// List godoc
// @Summary      商品列表
// @Description  商品列表
// @Tags         前台-商品
// @Accept       json
// @Produce      json
// @Success      200  {object}  types.BizVo{data=response.Product}
// @Router       /api/product/list [get]
// @Security ApiKeyAuth
func (h *ProductHandler) List(c *gin.Context) {
	var items []model.Product
	var list = make([]response.Product, 0)
	res := h.DB.Where("enabled", true).Order("sort_num asc").Find(&items)
	if res.Error == nil {
		for _, item := range items {
			var product response.Product
			err := utils.CopyObject(item, &product)
			if err == nil {
				product.Id = item.Id
				product.CreatedAt = item.CreatedAt.Unix()
				product.UpdatedAt = item.UpdatedAt.Unix()
				list = append(list, product)
			} else {
				log.Errorf("拷贝数据出现错误：%v", err)
			}
		}
	}
	utils.SUCCESS(c, list)
}
